/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.sd.jxta.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author SD
 */
public class FileUtil {

    private static BASE64Encoder encoder;
    private static BASE64Decoder decoder;


    static {
        encoder = new BASE64Encoder();
    }

    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

    public static byte[] getBytesFromFile(String path) throws IOException {
        return getBytesFromFile(new File(path));
    }

    public static void writeBytesIntoFile(String path, byte[] content) throws FileNotFoundException, IOException {

        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }

    public static String getBase64EncodeFromFile(String path) throws IOException {
        return encoder.encode(getBytesFromFile(path));
    }

    public static byte[] getBase64DecodeFromContentString(String content) throws IOException {
        return decoder.decodeBuffer(content);
    }

    // Deletes all files and subdirectories under dir.
    // Returns true if all deletions were successful.
    // If a deletion fails, the method stops attempting to delete and returns false.
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

    /**
     * Return the number of blocks a file can contain depending on the block size
     * @param file The file to get the blocks number
     * @param blockSize The size of the blocks
     * @return
     */
    public static int fileBlocksNumber(File file, int blockSize) {

        long fileSize = file.length();

        return (int) (fileSize / blockSize);
    }

    /**
     * Return the bytes from a block of a file,
     * 0 is the firs block
     * @param file The file to obtain the block of bytes
     * @param blockNumber The number of the block, 0 is the first
     * @param blockSize Size of the block
     * @return
     */
    public static byte[] getFileBlock(File file, int blockNumber, int blockSize) throws FileNotFoundException, IOException {

        FileInputStream in = new FileInputStream(file);
        return getStreamBlock(in, blockNumber, blockSize);
    }

    /**
     * Return the bytes from a block of a file,
     * 0 is the firs block
     * @param in The stream to obtain the block of bytes
     * @param blockNumber The number of the block, 0 is the first
     * @param blockSize Size of the block
     * @return
     */
    public static byte[] getStreamBlock(InputStream in, int blockNumber, int blockSize) throws IOException {
        byte[] buffer = new byte[blockSize];

        if (blockNumber < 0) {
            throw new IllegalArgumentException("Block number can't be negative");
        }

        if (blockSize < 0) {
            throw new IllegalArgumentException("Block size can't be negative");
        }

        in.read(buffer, blockNumber * blockSize, blockSize);

        return buffer;
    }

    /**
     * Serialize a object to a file
     * @param obj The object
     * @param file The file
     * @return
     */
    public static void serializeObjectToFile(Object obj, File file) throws IOException {
        System.out.println("Saving to file: " + file.getAbsolutePath());
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
        out.writeObject(obj);

    }

    /**
     * Deserialize a file to object
     * @param <T> Generic type for the method
     * @param file The file
     * @param type The class to convert the readed object
     * @return The object readed converted to the type especified with type
     * @throws java.io.IOException
     * @throws java.lang.ClassNotFoundException
     */
    public static <T> T deserializeFileToObject(File file, Class<T> type) throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        return (T) in.readObject();
    }
}
